package com.itkaien.javaeebased.networkprogerma;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MultipleForkSendFile  implements Runnable{

    // 客户端发送文件给服务器
    private Socket localhostSocker;

    public MultipleForkSendFile(Socket socket) {
        this.localhostSocker = socket;
    }

    public MultipleForkSendFile() {
    }

    @Override
    public void run() {
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("img_1.png"));
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(localhostSocker.getOutputStream());
            byte[] buffer=new byte[2048];
            int legth;
            while ((legth=bufferedInputStream.read(buffer)) != -1)  {
                bufferedOutputStream.write(buffer, 0, legth);
            }
            //最后一次刷盘操作，不然会缺少最后一次的数据
            bufferedOutputStream.flush();
//        bufferedOutputStream.close();
            localhostSocker.shutdownOutput();

            System.out.println("文件上传成功");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(localhostSocker.getInputStream()));
            String s = bufferedReader.readLine();
            System.out.println("接收消息:"+s);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (localhostSocker!= null){
                try {
                    localhostSocker.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
